package com.ruanxie.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruanxie.constant.HuebConstant.*;
import com.ruanxie.constant.MessageConstant;
import com.ruanxie.exception.HuebNotConnectException;
import com.ruanxie.json.jsonconverter.*;
import com.ruanxie.properties.CollegeProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.filters.RequestFilter;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.openqa.selenium.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;


//TODO 尝试：优化：(线程池或者连接池，可以试一试)（保证线程安全）配置多个浏览器驱动
/**
 *
 * 为每个线程创建独立的WebDriver
 * import org.openqa.selenium.WebDriver;
 * import org.openqa.selenium.chrome.ChromeDriver;
 * import org.openqa.selenium.chrome.ChromeOptions;
 *
 * import java.util.concurrent.LinkedBlockingQueue;
 * import java.util.concurrent.ThreadPoolExecutor;
 * import java.util.concurrent.TimeUnit;
 *
 * public class WebDriverPool {
 *
 *     private ThreadPoolExecutor executor;
 *
 *     public WebDriverPool(int poolSize) {
 *         executor = new ThreadPoolExecutor(poolSize, poolSize,
 *                 0L, TimeUnit.MILLISECONDS,
 *                 new LinkedBlockingQueue<Runnable>());
 *     }
 *
 *     public WebDriver getWebDriver() {
 *         return new ChromeDriver(createChromeOptions());
 *     }
 *
 *     private ChromeOptions createChromeOptions() {
 *         ChromeOptions options = new ChromeOptions();
 *         options.addArguments("--headless");
 *         options.addArguments("--disable-gpu");
 *         options.addArguments("--no-sandbox");
 *         return options;
 *     }
 *
 *     public void shutdown() {
 *         executor.shutdown();
 *         try {
 *             if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
 *                 executor.shutdownNow();
 *             }
 *         } catch (InterruptedException e) {
 *             executor.shutdownNow();
 *         }
 *     }
 * }
 *
 *
 *  使用线程池来管理
 * public class WebDriverPool {
 *
 *     private ThreadPoolExecutor executor;
 *
 *     public WebDriverPool(int poolSize) {
 *         executor = new ThreadPoolExecutor(poolSize, poolSize,
 *                 0L, TimeUnit.MILLISECONDS,
 *                 new LinkedBlockingQueue<Runnable>());
 *     }
 *
 *     public WebDriver getWebDriver() {
 *         return new ChromeDriver(createChromeOptions());
 *     }
 *
 *     private ChromeOptions createChromeOptions() {
 *         ChromeOptions options = new ChromeOptions();
 *         options.addArguments("--headless");
 *         options.addArguments("--disable-gpu");
 *         options.addArguments("--no-sandbox");
 *         return options;
 *     }
 *
 *     public void shutdown() {
 *         executor.shutdown();
 *         try {
 *             if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
 *                 executor.shutdownNow();
 *             }
 *         } catch (InterruptedException e) {
 *             executor.shutdownNow();
 *         }
 *     }
 * }
 */

/**
 *  模拟登录获取到河北经贸大学的cookie
 *  （这里不在按一开始功能设计那样的设计了，这里要加入各种spring的东西）
 *  作用：(后续会利用这个cookie获取到各种数据)
 *  设计：这里只打算用一个浏览器对象（其实是能new多个的，但是又不是很有必要，所以作为了bean对象了（默认单例））
 *  尝试优化：配置多个浏览器驱动
 */
@Component
@Slf4j
@Data
public class HuebUtil {
    //大部分东西都已经在bean对象配置了，直接依赖注入就行

    //抓包工具
    @Autowired
    private BrowserMobProxy browserMobProxy;//TODO 这里会添加过滤器，只抓特定请求
    //浏览器驱动(配置过的)
    @Autowired
    private WebDriver webDriver;

    //下面这些是base64相关，这里这些能存储在本地，这里测试的时候用得到，但是后续就用不到了

    //教务系统
        //这里原本想存下登录请求地址和验证码请求地址，但是想想其实这里复用性，不是很强，很多网站都是不一样的
        //验证码存储地址
//    private String captchaImgPath="captcha.jpg";


    //验证码使用的的是Base64编码，所以需要这个工具类
//    @Autowired
//    private Base64Util base64Util;//这里没扫描到会报错，主要就是放在这个test的锅

    /**
     * 获取当前登录界面的验证码
     */
    public String getCaptcha(){//TODO 赶时间：这里不做什么多线程多用户了，主打一个能显示就行
        //TODO 未解决：无法重复抓包同一个页面
        // 这里不知道为什么总是爆出Caught an exception on ProxyToServerConnection的异常
        // 解决：如果发现是同一个页面先换成别的页面在换回来
//        log.info(webDriver.getCurrentUrl());
        if (webDriver.getCurrentUrl().startsWith(HuebUrlConstant.LOGIN_URL)) {
//            log.info(webDriver.getCurrentUrl());
//            webDriver.get("https://example.com/");
            webDriver.get("data:,");
        } else if (webDriver.getCurrentUrl().startsWith(HuebUrlConstant.EDUCATIONA_ADMINISTRATION_MANAGEMENT_SYSTEM)) {
            webDriver.get(HuebUrlConstant.LOGOUT);
        }


        log.info("正在获取到河北经贸大学的验证码...");
        browserMobProxy.newHar();//用来抓取各种请求响应的格式
        // 添加过滤器只抓取特定的验证码请求
        browserMobProxy.addRequestFilter((RequestFilter) (request, contents, messageInfo) -> {
            if (request.getUri().startsWith(HuebUrlConstant.CAPTCHA)) {
               return (io.netty.handler.codec.http.HttpResponse) request;//继续请求
            } else {
                return null; // 忽略其他请求
            }
        });
        //当前请求的对应的操作
            //对响应拦截不需要，有这个反倒会有异常
//        browserMobProxy.addResponseFilter((ResponseFilter) (response, contents, messageInfo) -> {
//            String requestUrl = messageInfo.getUrl();
//            System.out.println(requestUrl);
//            if (requestUrl.startsWith(HuebUrlConstant.CAPTCHA)) {
////                base64Util.saveImg(contents.getTextContents(), captchaImgPath);
////                log.info(contents.getTextContents());
//                System.out.println(contents.getTextContents());
//
//            }
//        });



        //打开教务系统的登录界面
        webDriver.get(HuebUrlConstant.LOGIN_URL);//再退出再登录可行但是有点慢
            // 打开教务系统的登录界面（如果当前不在该页面）
            //这里目前是先打算牺牲点速度

//        webDriver.get(HuebUrlConstant.EDUCATIONA_ADMINISTRATION_MANAGEMENT_SYSTEM);
                    // 这个在没登陆的情况下能够跳转到登录界面，但是登录成功后，就没办法

        Har har=browserMobProxy.getHar();
        // 遍历请求条目请输出请求
            //最后就是List
//        final String[] captcha={null};//lambda 表达式（如 forEach）和匿名内部类不能直接修改外部的非 final 变量。
        AtomicReference<String> captcha=new AtomicReference<>();//用这个原子变量类，也能在lambda中修改变量
        har.getLog().getEntries().forEach(entry -> {
            String requestUrl = entry.getRequest().getUrl();
            log.info(requestUrl);
            if (requestUrl.startsWith(HuebUrlConstant.CAPTCHA)) {//验证码的请求开头
                //这些是测试代码
//                base64Util.saveImg(entry.getResponse().getContent().getText(),captchaImgPath);
//                log.info(entry.getResponse().getContent().getText());
//                System.out.println(requestUrl+"\n"+entry.getResponse().getContent().getText());

//                captcha[0]=entry.getResponse().getContent().getText();
                captcha.set(entry.getResponse().getContent().getText());
            }
        });
//        return captcha[0];
        return captcha.get();
    }

    /**
     * 从当前浏览器中获取请求体中的cookies形式
     * @return
     */
    public String changeCoookies(){
//        webDriver.get(HuebUrlConstant.EDUCATIONA_ADMINISTRATION_MANAGEMENT_SYSTEM);
        Set<Cookie> localDriverCookies = webDriver.manage().getCookies();
//        log.info(localDriverCookies.toString());
        String cookies="";
        for(Cookie cookie:localDriverCookies){
            cookies+=cookie.getName();
            cookies+='=';
            cookies+=cookie.getValue();
            cookies+=";";
        }
        return cookies;
    }

    //DONE 输入账号信息

    /**
     * 输入学生的账号信息，并且获取到cookie
     * @param studentId:学号
     * @param password:密码
     * @param captcha:验证码
     * @return : 河北经贸大学的cookie信息
     */
    public String getCookies(String studentId,String password,String captcha){
        log.info("正在填入账号信息...");
        //定位到账号密码验证码
        WebElement captchaWebElement=webDriver.findElement(new By.ByXPath(HuebLoginFormXpathConstant.CAPTCHA_XPATH));
                                        //((new By.ByXPath("//*[@id=\"captcha\"]")));
        captchaWebElement.sendKeys(captcha);
        //填写账号密码
        WebElement usernameWebElement = webDriver.findElement(new By.ByXPath(HuebLoginFormXpathConstant.USERNAME_XPATH));
                                        //(new By.ByXPath("//*[@id=\"username\"]"));
        WebElement passwordWebElement = webDriver.findElement(new By.ByXPath(HuebLoginFormXpathConstant.PASSWORD_XPATH));
                                        //(new By.ByXPath("//*[@id=\"password\"]"));
        usernameWebElement.sendKeys(studentId);
        passwordWebElement.sendKeys(password);
        //定位到提交组件
        WebElement submitWebElement = webDriver.findElement(new By.ByXPath(HuebLoginFormXpathConstant.SUBMIT_XPATH));
                                        //(new By.ByXPath("//*[@id=\"login_submit\"]"));
        submitWebElement.click();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        webDriver.get(HuebUrlConstant.EDUCATIONA_ADMINISTRATION_MANAGEMENT_SYSTEM);

        return changeCoookies();
    }

    /**
     *
     */
    public void Logout(){
        webDriver.get(HuebUrlConstant.LOGOUT);
    }
    //到这里通过proxy+selenium获取到cookie的结束


    //（获取到cookie后）从这里开始通过httpclient+fastjson解析出教务系统的各种数据
        //这里不管了，全部一起处理，效率会更高一点，但是分开处理感觉会更清楚一点，需要牺牲一点效率
        //TODO 尝试：优化：这里暂时先分开模块处理各种请求，这样其实会有点冗余
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private CollegeProperties collegeProperties;


    //DONE 尝试：优化：把网络请求这些函数代码给他抽象出来，太多相似代码了
    //      感觉也不难，但是就是有一些冗余数据不想处理
    /**
     * 从hueb中获取到学生基本信息
     * (课表返回的数据比较特殊，打算都单独写函数)
     * @param huebCookie
     * @return
     * @throws IOException
     */
    public HuebStudentJsonConverter getHuebStudentJsonConverter(String huebCookie) throws IOException {
        HttpPost httpPost = new HttpPost(HuebUrlConstant.COURCES_SCHEDULE_OF_STUDENT_URL);//这个似乎重复使用不了
        httpPost.setHeader(HuebRequestHeaderConstants.COOKIE_HEADER,huebCookie);
        List<NameValuePair> params = new ArrayList<>();
        //这里发现需要获取到学年名，虽然还是有挺多种方法可以获取，或者设置，但是这里选择直接从学号解析出来（这样其实是有一定风险的）
        params.add(new BasicNameValuePair(HuebRequestParamConstants.SCHOOL_YEAR_PARAM,collegeProperties.getNowSchoolYear()));
        params.add(new BasicNameValuePair(HuebRequestParamConstants.TERM_PARAM,collegeProperties.getNowTerm()));
        // 将参数编码为表单实体
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        //httpclient在连接多次后，会出现阻塞问题，必须要释放连接，下面这个是手动释放
//        // 执行 HTTP Post 请求
//        HttpResponse response = httpClient.execute(httpPost);
//        // 获取响应状态码
//        int statusCode = response.getStatusLine().getStatusCode();
////        System.out.println("Response Code: " + statusCode);
//        if(statusCode != 200){
//            throw new HuebNotConnectException(MessageConstant.HUEB_NOT_CONNECT_ERROR);
//        }
//
//        // 处理响应
//        HttpEntity entity = response.getEntity();
//        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
////        System.out.println(rd.readLine());
//        String responseJsonString=rd.readLine();
//
//        //必须要释放连接，否则会出现httpclient阻塞
//        rd.close();
//        entity.getContent().close();
//        httpPost.releaseConnection();
//
//
//        //处理成类
//        JSONObject jsonObject= JSONObject.parseObject(responseJsonString);
//        HuebStudentJsonConverter huebStudentJsonConverter =jsonObject.getObject(HuebResponseJsonConstant.CLASS_SCHEDULE_URL_STUDENT_INFO_NAME, HuebStudentJsonConverter.class);
//        return huebStudentJsonConverter;
        //自动释放连接:
        try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    // 执行 HTTP Post 请求
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
    //        System.out.println("Response Code: " + statusCode);
            if(statusCode != 200){
                throw new HuebNotConnectException(MessageConstant.HUEB_NOT_CONNECT_ERROR);
            }

            // 处理响应
            HttpEntity entity = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
    //        System.out.println(rd.readLine());
            String responseJsonString=rd.readLine();

//            //必须要释放连接，否则会出现httpclient阻塞
//            rd.close();
//            entity.getContent().close();
//            httpPost.releaseConnection();


            //处理成类
            JSONObject jsonObject= JSONObject.parseObject(responseJsonString);
            HuebStudentJsonConverter huebStudentJsonConverter =jsonObject.getObject(HuebResponseJsonConstant.CLASS_SCHEDULE_URL_STUDENT_INFO_NAME, HuebStudentJsonConverter.class);
            return huebStudentJsonConverter;
        }
    }

    //DONE 待做：提取出共性的代码
    /**
     * (通过泛型)提取出河北经贸大学公共的httpclient请求代码
     *      * 条件：
     *      * 1.请求方式为post
     *      * 2.返回的json为：{..,"items":[{},{},{},..]}，需要的数据在items中，为一个数组
     * @param ：对应的请求网址
     * @param huebCookie：对应学生获取到的cookie
     * @param params：请求体中的内容
     * @param clazz
     * @return : 返回的是T这个类型的结果数组
     * @param <T>
     * @throws IOException
     */
    public <T> List<T> getHuebJsonConverterObject(String huebUrl,String huebCookie,List<NameValuePair> params,Class<T> clazz) throws IOException{
        //通过httpclient发起请求
        HttpPost httpPost = new HttpPost(huebUrl);
        httpPost.setHeader(HuebRequestHeaderConstants.COOKIE_HEADER,huebCookie);
            // 将参数编码为表单实体
        if(params != null){
            httpPost.setEntity(new UrlEncodedFormEntity(params));
        }
        // 使用 try-with-resources 确保资源自动关闭，防止出现阻塞状态
            // 执行 HTTP Post 请求
        try(CloseableHttpResponse response = httpClient.execute(httpPost)){
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
//        System.out.println("Response Code: " + statusCode);
            if(statusCode != 200){
                throw new HuebNotConnectException(MessageConstant.HUEB_NOT_CONNECT_ERROR);
            }
            // 处理响应
            HttpEntity entity = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
            String responseJsonString=rd.readLine();
//            //必须要释放连接，否则会出现httpclient阻塞
//            rd.close();
//            entity.getContent().close();
//            httpPost.releaseConnection();
            //DONE 测试
//        System.out.println(responseJsonString);
            //通过fastjson转化为实体类
            JSONObject jsonObject = JSON.parseObject(responseJsonString);
            JSONArray itemsArray = jsonObject.getJSONArray(HuebResponseJsonConstant.RESULT_NAME);
            List<T> jsonConverterObejctList = itemsArray.toJavaList(clazz);
            return jsonConverterObejctList;
        }
    }

    //DONE 还没写完，还需要在测试下，需要传入什么参数
    //没有泛型前的代码(同时还有部分代码没有写完)
//    public HuebTeachingPlanInfoJsonConverter getHuebTeachingPlanInfoJsonConverter(String cookie) throws IOException{
//        HttpPost httpPost = new HttpPost(HuebUrlConstant.CLASS_SCHEDULE_URL);
//        httpPost.setHeader(HuebRequestHeaderConstants.COOKIE_HEADER,cookie);
//        List<NameValuePair> params = new ArrayList<>();
//        //这里发现需要获取到学年名，虽然还是有挺多种方法可以获取，或者设置，但是这里选择直接从学号解析出来（这样其实是有一定风险的）
//        params.add(new BasicNameValuePair(HuebRequestParamConstants.SCHOOL_YEAR_PARAM,collegeProperties.getNowSchoolYear()));
//        params.add(new BasicNameValuePair(HuebRequestParamConstants.TERM_PARAM,collegeProperties.getNowTerm()));
//        // 将参数编码为表单实体
//        httpPost.setEntity(new UrlEncodedFormEntity(params));
//
//        // 执行 HTTP Post 请求
//        HttpResponse response = httpClient.execute(httpPost);
//
//
//        // 获取响应状态码
//        int statusCode = response.getStatusLine().getStatusCode();
////        System.out.println("Response Code: " + statusCode);
//        if(statusCode != 200){
//            throw new HuebNotConnectException(MessageConstant.HUEB_NOT_CONNECT_ERROR);
//        }
//
//        // 处理响应
//        HttpEntity entity = response.getEntity();
//        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
////        System.out.println(rd.readLine());
//        String responseJsonString=rd.readLine();
//
//        JSONObject jsonObject = JSON.parseObject(responseJsonString);
//        JSONArray itemsArray = jsonObject.getJSONArray(HuebResponseJsonConstant.RESULT_NAME);
//        List<HuebTeachingPlanInfoJsonConverter> teachingPlanInfoJsonConverterList = itemsArray.toJavaList(HuebTeachingPlanInfoJsonConverter.class);
//
//        if (!teachingPlanInfoJsonConverterList.isEmpty()) {
//            return teachingPlanInfoJsonConverterList.get(0);
//        } else {
//            throw new NoSuchElementException("No elements found in the items array");
//        }
//    }

    /**
     * 获取到教学执行计划中专业相关的信息
     * @param huebCookie
     * @param yearOfEntry
     * @param majorId
     * @return
     * @throws IOException
     */
    public HuebTeachingPlanInfoJsonConverter getHuebTeachingPlanInfoJsonConverter(String huebCookie,String yearOfEntry,String majorId) throws IOException{
        //设置对应的请求体
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(HuebRequestParamConstants.YEAR_OF_ENTRY_ID_PARAM,yearOfEntry));
        params.add(new BasicNameValuePair(HuebRequestParamConstants.MAJOR_ID_PARAM,majorId));
//        log.info(huebCookie+"\n");
//        log.info("{}\n{}\n{}",HuebUrlConstant.TEACHING_PLAN_INFO_URL,huebCookie,params);

        //发起请求，并且获取到对应的实体类
        List<HuebTeachingPlanInfoJsonConverter> teachingPlanInfoJsonConverterList=  getHuebJsonConverterObject(HuebUrlConstant.TEACHING_PLAN_INFO_URL,huebCookie,params,HuebTeachingPlanInfoJsonConverter.class);

        //只需要第一个就行
        if (!teachingPlanInfoJsonConverterList.isEmpty()) {
            return teachingPlanInfoJsonConverterList.get(0);
        } else {
            throw new NoSuchElementException("No elements found in the items array");
        }
    }

    /**
     * 获取到河北经贸大学中专业对应的教学执行计划的完整课程信息（包括部分课程信息和教学执行计划课程信息）
     * @param huebCookie
     * @param teachingPlanInfoId
     * @return
     * @throws IOException
     */
    public List<HuebTeachingPlanCourseInfoJsonConverter> getHuebTeachingPlanCourseInfoJsonConverterList(String huebCookie,String teachingPlanInfoId) throws IOException {
        //设置对应的请求体
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(HuebRequestParamConstants.TEACHING_PLAN_INFO_ID_PARAM,teachingPlanInfoId));
        params.add(new BasicNameValuePair(HuebRequestParamConstants.REVIEW_STATUS_PARAM,null));
        params.add(new BasicNameValuePair(HuebRequestParamConstants.QUERY_MODEL_SHOW_COUNT_PARAM,HuebRequestParamConstants.QUERY_MODEL_SHOW_COUNT_PARAM_MAX_VALUE));

        //发起请求，并且获取到对应的实体类
        List<HuebTeachingPlanCourseInfoJsonConverter> teachingPlanCourseInfoJsonConverterList=  getHuebJsonConverterObject(HuebUrlConstant.TEACHING_PLAN_COURSE_INFO_URL,huebCookie,params,HuebTeachingPlanCourseInfoJsonConverter.class);
        return teachingPlanCourseInfoJsonConverterList;
    }

    public List<HuebCourseGradeOfStudentJsonConvert> getHuebCourseGradeOfStudentJsonConvertList(String huebCookie, String schoolYear, String term) throws IOException {
        //设置对应的请求体
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(HuebRequestParamConstants.QUERY_MODEL_SHOW_COUNT_PARAM,HuebRequestParamConstants.QUERY_MODEL_SHOW_COUNT_PARAM_MAX_VALUE));
        //可以为空，但是一定要传
        params.add(new BasicNameValuePair(HuebRequestParamConstants.SCHOOL_YEAR_PARAM,schoolYear));
        params.add(new BasicNameValuePair(HuebRequestParamConstants.TERM_PARAM,term));

        //发请求获取json数据，并转为实体类
        List<HuebCourseGradeOfStudentJsonConvert> currentHuebCourseGradeOfStudentJsonConvertsList=getHuebJsonConverterObject(HuebUrlConstant.COURCES_GRADE_OF_STUDENT_URL,huebCookie,params, HuebCourseGradeOfStudentJsonConvert.class);
        return currentHuebCourseGradeOfStudentJsonConvertsList;
    }


    //涉及到课表的都有点特殊，因为它返回的json有点特殊，代码跟上面请求课表的没有很大的区别

    /**
     * 获取到学生当前学年当前学期的课表数据
     * @param huebCookie
     * @return
     * @throws IOException
     */
    public HuebCourseScheduleOfStudentJsonConvert getHuebCourseScheduleOfStudentJsonConvert(String huebCookie) throws IOException {
        HttpPost httpPost = new HttpPost(HuebUrlConstant.COURCES_SCHEDULE_OF_STUDENT_URL);//这个似乎重复使用不了
        httpPost.setHeader(HuebRequestHeaderConstants.COOKIE_HEADER,huebCookie);
        List<NameValuePair> params = new ArrayList<>();
        //这里发现需要获取到学年名，虽然还是有挺多种方法可以获取，或者设置，但是这里选择直接从学号解析出来（这样其实是有一定风险的）
        params.add(new BasicNameValuePair(HuebRequestParamConstants.SCHOOL_YEAR_PARAM,collegeProperties.getNowSchoolYear()));
        params.add(new BasicNameValuePair(HuebRequestParamConstants.TERM_PARAM,collegeProperties.getNowTerm()));
        // 将参数编码为表单实体
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        //自动释放连接:
        try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 执行 HTTP Post 请求
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            //        System.out.println("Response Code: " + statusCode);
            if(statusCode != 200){
                throw new HuebNotConnectException(MessageConstant.HUEB_NOT_CONNECT_ERROR);
            }
            // 处理响应
            HttpEntity entity = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
            //        System.out.println(rd.readLine());
            String responseJsonString=rd.readLine();
            //处理成类
            HuebCourseScheduleOfStudentJsonConvert huebStudentJsonConverter= JSONObject.parseObject(responseJsonString,HuebCourseScheduleOfStudentJsonConvert.class);
            return huebStudentJsonConverter;
        }
    }
}
